#!/usr/bin/perl -w
use strict;
use Getopt::Long;

#88888888888888888888888888888888888888888888888888888888888888888888888888888888

#	Usage

#88888888888888888888888888888888888888888888888888888888888888888888888888888888

my $usage = <<'USAGE';

USAGE:

    short_to_long_names.pl
                --name_map SHORT_NAMES_TO_LONG.FILE
                [--verbose]
				[--help]

    Iterates through files and substitutes long names for short names 
        according to the supplied mapping file.

	The mapping file is tab-delimited in 2 columns with the short names
	in the first column and the long names in the second.

	Prints to STDOUT

USAGE


#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#	Get options

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
# mandatory
my $name_map;
my $verbose;
# optional parameters
my $help;
GetOptions(
			'verbose'		=> \$verbose,
			'name_map=s'	=> \$name_map,
			'help'			=> \$help);

die $usage if ($help);
die $usage unless ($name_map);
my %lookup;
{
	open LOOKUP_FILE, $name_map or die "Error!\n\tCould not open $name_map\n$!\n";
	for (<LOOKUP_FILE>)
	{
		chomp;
		next unless /([^\t]+)\t(.+)/;
		$lookup{$1} = $2;
	}
}

for (@ARGV)
{
	die "Error:\n\t$_ does not exists.\n" unless -f $_;
}
if ($verbose)
{
	my $cnt_changes = 0;
	for (<>)
	{
		my @found = /(XYZX\d+)/g;
		for my $found(@found)
		{
			#print STDERR "-";
			if (exists $lookup{$found})
			{
				s/$found/$lookup{$found}/;
				$cnt_changes++;
				#print STDERR ">";
			}
		}
		print;
	}
	print STDERR "\n";
	print STDERR "\t$cnt_changes\tsubstitutions made.\n";
}
else
{
	for (<>)
	{
		my @found = /(XYZX\d+)/g;
		for my $found(@found)
		{
			if (exists $lookup{$found})
			{
				s/$found/$lookup{$found}/;
			}
		}
		print;
	}
}


